import fs from 'fs';
import path from 'path';
import Jimp from 'jimp';
import axios from 'axios';
import { connection } from '../app/database/mysql';
import { houseModal } from './house.model';
import { APP_URL, STATIC_PATH } from '../app/app.config';
import { geByIdtMovieCategory, getIdCategory, getIdCountry } from '../category/category.service';
import { getTokenCookie } from '../tokenCookie/tokenCookie.service';
import { getVideoUrlWai } from '../videoPlay/videoPlay.service';
import { getActorsById } from '../actor/actor.service';

/**
 * 获取内容
 */
export interface GetHouseOptionsPagination {
  limit?: number;
  offset?: number;
}

export const getMovice = async (
  status: number,
  is_multiset: number,
  recommend: number,
  countryId: number,
  popular: number,
  pageSize:number,
  pageNo: number,
  userId: number,
  is_free: number,
  play_year: number,
  language_type: number,
  categoryId: number,
  keyWord: any)=> {
  // 准备查询
  let statement = `
    SELECT SQL_CALC_FOUND_ROWS *, COUNT(id) OVER () AS total FROM movies
  `;
  let where = []
  if (status >= 0) {
    where.push(`status = `+status)
  }
  if (is_multiset >=0){
    where.push(`is_multiset = ` + is_multiset)
  }
  if (recommend >= 0) {
    where.push(`recommend = ` + recommend)
  }
  if (countryId >=0){
    where.push(`FIND_IN_SET(${countryId}, country)`)
  }
  if (popular >= 0) {
    where.push(`popular = ` + popular)
  }
  if (userId>0) {
    where.push(`user_id = ` + userId)
  }
  if (is_free >= 0) {
    where.push(`is_free = ` + is_free)
  }
  if (play_year >= 0) {
    where.push(`play_year = ` + play_year)
  }
  if (language_type >= 0) {
    where.push(`FIND_IN_SET(${language_type}, language_type)`)
  }
  if (keyWord != '') {
    where.push(`name LIKE '${keyWord}%' OR name_zh LIKE '${keyWord}%'`)
  }
  if (categoryId >= 0) {
    where.push(`FIND_IN_SET(${categoryId}, category)`)
  }
  if (where.length>0) {
    statement += ` where `
    for(let i=0; i<where.length; i++) {
      statement += where[i]
      if (i<where.length-1) {
        statement += ` and `
      }
    }
  }
  statement += ` ORDER by sort_num DESC, id DESC limit `+(pageNo>0?(pageNo-1)*pageSize:0) + `,` +pageSize
  
  // 执行查询
  const [data] = await connection.promise().query(statement);

  let totalCount: any;
  if (data[0] && data[0].total) totalCount = data[0].total;
  let totalPage = (totalCount % pageSize) > 0 ? parseInt(`${totalCount / pageSize}`)+1 : totalCount / pageSize

  for(let item of data as any) {
    // 添加多集
    if (item.is_multiset == 1) {
      item.multiSet = await getMultiset(item.id, item.is_bolum)
    }

    let categoryNumbers = [];
    if (item.category) {
      categoryNumbers = await item.category.match(/\d+(\.\d+)?/g);
      categoryNumbers = categoryNumbers.map(Number);
    }

    let countryNumbers = [];
    if (item.country) {
      countryNumbers = await item.country.match(/\d+(\.\d+)?/g);
      countryNumbers = countryNumbers.map(Number);
    }

    let language_typeNumbers = [];
    if (item.language_type) {
      language_typeNumbers = await item.language_type.match(/\d+(\.\d+)?/g);
      language_typeNumbers = language_typeNumbers.map(Number);
    }

   
    item.country = countryNumbers;
    item.category = categoryNumbers;
    item.language_type = language_typeNumbers;
  }

  for (let i of data as any) {
    if (i.category && i.category.length > 0) {
      let category_arr = [];
      for (let e of i.category) {
        let category_dan = await geByIdtMovieCategory(e)
        category_arr.push(category_dan);
      }
      i.category = category_arr;
    }

    if (i.country && i.country.length > 0) {
      let country_arr = [];
      for (let e of i.country) {
        let country_dan = await getIdCountry(e)
        country_arr.push(country_dan);
      }
      i.country = country_arr;
    }
  }

  // 添加演员
  for (let e of data as any) {
    let actor_arr = [];
    if (e.actors) {
      let actorIdArr = e.actors.split(',').map(Number);
      for (let acId of actorIdArr) {
        let actor = await getActorsById(acId);
        actor_arr.push(actor[0]);
      }
      e.actorsName = actor_arr;
    }
  }
  
  let res = {
    data,
    totalPage,
    totalCount
  }
  // 提供数据
  return res;
}

/**
 * 随机获取电影
 */
export const getRandomHouse = async (categoryId: number, recommend: number, status: number, pageSize: number ) => {
  // 准备查询
  let statement = `
    SELECT * FROM movies
  `;
  
  let where = []
  if (status >= 0) {
    where.push(`status = ` + status)
  }
  if (recommend >= 0) {
    where.push(`recommend = ` + recommend)
  }
  if (categoryId >= 0) {
    where.push(`FIND_IN_SET(${categoryId}, category)`)
  }
  if (where.length > 0) {
    statement += ` where `
    for (let i = 0; i < where.length; i++) {
      statement += where[i]
      if (i < where.length - 1) {
        statement += ` and `
      }
    }
  }
  statement += ` ORDER BY RAND() LIMIT ${pageSize} `

  // 执行查询
  const [data] = await connection.promise().query(statement);

  for (let item of data as any) {
    let categoryNumbers = [];
    if (item.category) {
      categoryNumbers = await item.category.match(/\d+(\.\d+)?/g);
      categoryNumbers = categoryNumbers.map(Number);
    }

    let countryNumbers = [];
    if (item.country) {
      countryNumbers = await item.country.match(/\d+(\.\d+)?/g);
      countryNumbers = countryNumbers.map(Number);
    }


    item.country = countryNumbers;
    item.category = categoryNumbers;
  }

  for (let i of data as any) {
    if (i.category && i.category.length > 0) {
      let category_arr = [];
      for (let e of i.category) {
        let category_dan = await geByIdtMovieCategory(e)
        category_arr.push(category_dan);
      }
      i.category = category_arr;
    }

    if (i.country && i.country.length > 0) {
      let country_arr = [];
      for (let e of i.country) {
        let country_dan = await getIdCountry(e)
        country_arr.push(country_dan);
      }
      i.country = country_arr;
    }
  }

  // 提供数据
  return data;
}

/**
 * 按 ID 获取内容
 */
export const getIdHouse = async (postId: number) => {
  // 准备查询
  const statement = `
    SELECT * FROM movies
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, postId);
  let house = data[0] as any;

  // 添加多集
  if (house.is_multiset == 1) {
    let multiSet: any = await getMultiset(house.id, house.is_bolum);
    let multiSets = [];

    if (multiSet[0].url) {
      let multiSetUrl = multiSet[0].url;
      if (multiSetUrl.startsWith('wxv')) {
        house.videoUrl = await getVideoUrlWai(multiSet[0].url);
      } else {
        house.videoUrl = multiSetUrl;
      }
    }

    // if (multiSet[0].url) {
    //   house.videoUrl = await getVideoUrlWai(multiSet[0].url);
    // } else {
    //   house.videoUrl = multiSet[0].other_url;
    // }

    for (let item of multiSet) {
      multiSets.push(item);
    }
    house.multiSets = multiSets;
  } else {
    if(house.url) {
      house.videoUrl = await getVideoUrlWai(house.url); // 公众号视频地址
    } else {
      house.videoUrl = house.other_url; // 其他视频地址
    }
    
  }

  // 获取电影类型
  let categoryNames = [];
  for (let item of data[0].category.match(/\d+/g)) {
    let category = await getIdCategory(parseInt(item, 10));
    if (category) {
      categoryNames.push(category.name);
    }
  }
  if (categoryNames.length > 0) {
    data[0].category = categoryNames;
  }

  // 获取制作国
  let countryNames = [];
  for (let item of data[0].country.match(/\d+/g)) {
    let country = await getIdCountry(parseInt(item, 10));
    if (country) {
      countryNames.push(country.name);
    }
  }
  if (countryNames.length > 0) {
    data[0].country = countryNames;
  };

  // 提供数据
  return house;

  // 获取 token_cookie
  // const getToken_cookie = await getTokenCookie();
  // const cookieData = getToken_cookie.data[0].cookie;
  // for (let item of data as any) {
  //   const url = `https://mp.weixin.qq.com/cgi-bin/video?action=get_mp_video_play_url&vid=` + item.url + `&token=${ getToken_cookie.data[0].token }`;
  //   const resp = await axios({
  //     method: "GET",
  //     url: url,
  //     headers: {
  //       withCredentials: true,
  //       "Access-Control-Allow-Credentials":true,
  //       'content-type':'application/json',
  //       'Cookie': cookieData
  //     }
  //   }).then(async res => {
  //     let videos = await res.data.url_info;
  //     if (videos && videos.length > 0) {
  //       let videoStrUrl = videos[0].url
  //       item.videoUrl = videoStrUrl.replace("mpvideo.qpic.cn", "wxsnsdy.wxs.qq.com/130/20210/snssvpdownload/SH/reserved", videoStrUrl)
  //       // item.videoUrl = videos[0].url;
  //     }
  //   }).catch(err => {
  //     console.error("err: ", err);
  //   })

  //   // let videos = await resp.data.url_info;
  //   // if (videos && videos.length > 0) {
  //   //   item.videoUrl = videos[0].url
  //   // }
    
  //   const categoryName = await getIdCategory(item.type)
  //   const nationality = await getIdCategory(item.attributes)
  //   if (categoryName && categoryName.name) item.category_name = categoryName.name
  //   if (nationality && nationality.name) item.nationality_name = nationality.name
  // }

  // // 提供数据
  // return house;
}

/**
 * 获取电影(按 ID) 后台专用
 */
export const getMovieById = async (postId: number) => {
  // 准备查询
  const statement = `
    SELECT * FROM kitap
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, postId);

  for (let item of data as any) {
    // 添加多集
    if(item.is_bound == 1) {

    }
    item.multiSet = await getMultiset(item.id, item.is_bolum);

    // بۆلۈم
    item.bolumArr = await getBolum(item.id);
  }

  // 提供数据
  return data;
}

/**
 * 按 ID 获取电影封面
 */
export const getMoviePicture = async (postId: number) => {
  // 准备查询
  const statement = `
    SELECT image_url FROM movies
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, postId);

  // 提供数据
  return data;
}

/**
 * 获取新电影
 */
export const getRecentlyMovie = async (playTime: number, pageNo: number, pageSize: number) => {
  // 准备查询
  let statement = `
    SELECT SQL_CALC_FOUND_ROWS *, COUNT(id) OVER () AS total FROM movies
    WHERE playTime > ?
  `;

  statement += ` ORDER by id DESC, id DESC limit ` + (pageNo > 0 ? (pageNo - 1) * pageSize : 0) + `,` + pageSize

  // 执行查询
  const [data] = await connection.promise().query(statement, playTime);

  let totalCount: any;
  if (data[0] && data[0].total) totalCount = data[0].total;
  let totalPage = (totalCount % pageSize) > 0 ? parseInt(`${totalCount / pageSize}`) + 1 : totalCount / pageSize

  for (let item of data as any) {
    // 添加多集
    if (item.is_multiset == 1) {
      item.multiSet = await getMultiset(item.id, item.is_bolum)
    }

    let categoryNumbers = [];
    if (item.category) {
      categoryNumbers = await item.category.match(/\d+(\.\d+)?/g);
      categoryNumbers = categoryNumbers.map(Number);
    }

    let countryNumbers = [];
    if (item.country) {
      countryNumbers = await item.country.match(/\d+(\.\d+)?/g);
      countryNumbers = countryNumbers.map(Number);
    }


    item.country = countryNumbers;
    item.category = categoryNumbers;
  }

  for (let i of data as any) {
    if (i.category && i.category.length > 0) {
      let category_arr = [];
      for (let e of i.category) {
        let category_dan = await geByIdtMovieCategory(e)
        category_arr.push(category_dan);
      }
      i.category = category_arr;
    }

    if (i.country && i.country.length > 0) {
      let country_arr = [];
      for (let e of i.country) {
        let country_dan = await getIdCountry(e)
        country_arr.push(country_dan);
      }
      i.country = country_arr;
    }
  }

  let res = {
    data,
    totalPage,
    totalCount
  }
  // 提供数据
  return res;
}


/**
 * 按关键字获取（模糊查询） 后期优化暂时不用
 */
export const byKeyWordSelect = async (keyWord: any) => {
  // 准备查询
  const statement = `
    SELECT * FROM movies
    WHERE name LIKE '${keyWord}%' OR name_zh LIKE '${keyWord}%'
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, keyWord);

  // 提供数据
  return data;
}

/**
 * 创建内容
 */
export const createMovie = async (post: houseModal) => {
  // 准备查询
  const statement = `
    INSERT INTO movies
    SET ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, post);

  // 提供数据
  return data;
}

/**
 * 创建多集
 */
export const createMultisetMovie = async (post: houseModal) => {
  // 准备查询
  const statement = `
    INSERT INTO audioBooks
    SET ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, post);

  // 提供数据
  return data;
}

/**
 * 获取多集
 */
export const getMultiset = async (postId: number, is_bolum: number) => {
  // 准备查询
  // const statement = `
  //   SELECT * FROM audioBooks
  //   WHERE book_id = ?
  // `;

  let statement = `
    SELECT * FROM audioBooks
  `;
  let where = []
  if (postId >= 0) {
    where.push(`book_id = ` + postId)
  }
  if (is_bolum > 0) {
    where.push(`bolum_id = ` + is_bolum)
  }
  if (where.length > 0) {
    statement += ` where `
    for (let i = 0; i < where.length; i++) {
      statement += where[i]
      if (i < where.length - 1) {
        statement += ` and `
      }
    }
  }

  // 执行查询
  const [data] = await connection.promise().query(statement);;

  // 提供数据
  return data;
}

/**
 * 更新多集
 */
export const updateMultisetMovie = async (post: houseModal, postId: number) => {
  // 准备查询
  const statement = `
    UPDATE audioBooks
    SET ?
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, [post, postId]);

  // 提供数据
  return data;
}

/**
 * 获取多集电影的会员状况
 */
export const getMultisetIsVip = async (postId: number) => {
  // 准备查询
  const statement = `
    SELECT is_free
    FROM multiset
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, [postId]);

  // 提供数据
  return data;
}

/**
 * 更新内容
 */
export const updateHouse = async (post: houseModal, postId: number) => {
  // 准备查询
  const statement = `
    UPDATE movies
    SET ?
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, [post ,postId]);

  // 提供数据
  return data;
}

/**
 * 删除内容
 */
export const deleteMovie = async (postId: number) => {
  // 准备查询
  const statement = `
    DELETE FROM kitap
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, postId);

  // 提供数据
  return data;
}

/**
 * 状态
 */
export const houseStatusChange = async (postId: number, post: any) => {
  // 准备数据
  const statement = `
    UPDATE kitap
      SET ?
      WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, [post, postId]);

  // 提供数据
  return data;
};

/**
 * 存储文件信息
 */
export const createFile = async (
  file: houseModal
) => {
  // 准备查询
  const statement = `
    INSERT INTO resource
    SET ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, file);

  // 提供数据
  return data;
};

/**
 * 更新文件信息
 */
export const updateFile = async (post: houseModal, postId: number)=>{
  const statement = `
    UPDATE resource
    SET ?
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, [post,postId]);

  // 提供数据
  return data;
}

/**
 * 按 ID 查找文件
 */
export const findFileById = async (fileId: number, targetId: number, type: number, ...size: any) => {
  // 准备查询
  let sql = 'SELECT * FROM resource ';
  let and = false;
  if (fileId > 0) {
    sql += " where id = "+fileId;
    and = true;
  }
  if(targetId > 0) {
    sql += (and?" and ":" where ") + " target_id = "+targetId;
    and = true;
  }
  if (type > 0) {
    sql += (and ? " and " : " where ") + " target_type = "+type;
  }
  
  // 执行查询
  const [data] = await connection.promise().query(sql);
  for (let item of data as any) {
    if (size && size.length > 0) {
      item.fullUrl = APP_URL + item.url + '/resized/' + item.filename + "-" + size[0]
    } else {
      item.fullUrl = APP_URL + item.url + item.filename
    }
  }
  
  // 提供数据
  return data as any;
}

/**
 * 删除内容文件
 */
export const deleteFileById = async (file:houseModal)=>{
  if(!file.id || file.id<=0)return
  const statement = `delete from resource where id = ?`;
  const [data] = await connection.promise().query(statement,file.id);
  if((data as any).affectedRows>0){
    let path = STATIC_PATH+file.url + file.filename
    
    try {
      fs.unlinkSync(path);
    } catch (error) {
      console.log("fileDeleteErr:",error);
    }
  };
  
}

/**
 * 调整图像尺寸
 */
export const imageResizer = async (
  image: Jimp,
  file: Express.Multer.File
) => {
  if (image['_exif'] == null) return

  // 图像尺寸
  const { imageSize } = image['_exif'];


  // 文件路径
  const filePath = path.join(file.destination, 'resized/', file.filename);

  // 大尺寸
  if (imageSize.width > 1080) {
    image
      .resize(1080, Jimp.AUTO)
      .quality(85)
      .write(`${filePath}-lerge`);
  }

  // 中等尺寸
  if (imageSize.width > 440) {
    image
      .resize(440, Jimp.AUTO)
      .quality(95)
      .write(`${filePath}-medium`);
  }

  // 缩略图
  if (imageSize.width > 320) {
    image
      .resize(320, Jimp.AUTO)
      .quality(85)
      .write(`${filePath}-thumbnail`);
  }
}

/**
 * كىتاب ئىچىدىكى بۆلۈم
 */
export const getBolum = async (postId: number) => {
  // 准备查询
  const statement = `
    SELECT * FROM in_book_bolum
    WHERE book_id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, postId);
  

  // 提供数据
  return data;
}
